from django.http import JsonResponse
from django.views import View
from rest_framework import status
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, DestroyAPIView
from rest_framework.response import Response

from question.utils import get_user_dict
from recruit.models import Recruit, Enterprise
from recruit.serializers.recruits import RecruitsSearchRecommendSerializer, RecruitsSearchCityKeywordSerializer, \
    RecruitsIdSerializer
from users.models import User


class RecruitsSearchRecommendView(ListAPIView):
    """推荐职位"""
    serializer_class = RecruitsSearchRecommendSerializer
    queryset = Recruit.objects.all().order_by('-salary')[:4]

    def list(self, request, *args, **kwargs):
        # 获取查询集
        queryset = self.filter_queryset(self.get_queryset())
        # 获取序列化器
        serializer = self.get_serializer(queryset, many=True)
        data_dict = serializer.data

        for data in data_dict:
            logo = data['enterprise']['logo']

            # 修改logo地址
            data['enterprise']['logo'] = logo.replace('8000/recruits/search/latest/', '8888/')

        return Response(data_dict)


# 最新职位
class RecruitsSearchLatestView(ListAPIView):
    serializer_class = RecruitsSearchRecommendSerializer
    queryset = Recruit.objects.all().order_by('-createtime')[:4]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)

        data_dict = serializer.data

        for data in data_dict:
            logo = data['enterprise']['logo']

            # 修改logo地址
            data['enterprise']['logo'] = logo.replace('8000/recruits/search/latest/', '8888/')

        return Response(data_dict)


# 搜索职位
class RecruitsSearchCityKeywordView(CreateAPIView, ListAPIView):
    serializer_class = RecruitsSearchCityKeywordSerializer

    def get_queryset(self):
        # 获取查询条件
        keyword = self.request.data.get('keyword')
        city = self.request.data.get('cityname')
        if keyword is None or keyword == '':
            # 全部数据
            return Recruit.objects.filter(city=city).order_by('id')

        # 搜索结果
        return Recruit.objects.filter(jobname__contains=keyword, city=city).order_by('id')

    def create(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        return Response(serializer.data, status=status.HTTP_201_CREATED)



class RecruitsIdView(ListAPIView):
    serializer_class = RecruitsIdSerializer

    def get_queryset(self):
        # 获取查询条件
        id = self.kwargs.get('id', None)

        if not id:
            return Recruit.objects.all()

        recuit = Recruit.objects.filter(id=id)
        return recuit

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        data_dict = serializer.data
        # 获取企业对象
        enterprise = Enterprise.objects.get(id=data_dict[0]['id'])

        logo = data_dict[0]['enterprise']['logo']
        logo = logo.replace(f'8000/recruits/{data_dict[0]["id"]}/', '8888/')
        data_dict[0]['enterprise']['logo'] = logo

        # 渲染数据
        recruits = data_dict[0]['enterprise']['recruits']
        for i in recruits:
            # 修改数据
            i['enterprise']['recruits'] = [enterprise.recruits.all().count()]
            logo = i['enterprise']['logo']
            logo = logo.replace(f'8000/recruits/{data_dict[0]["id"]}/', '8888/')
            i['enterprise']['logo'] = logo

        # 返回响应
        return Response(data_dict[0])


# 增加职位访问次数
class RecruitsIdVisitView(View):

    def put(self, request, id):
        try:
            recruits = Recruit.objects.get(id=id)
            recruits.visits += 1
            recruits.save()
            return JsonResponse({'message': '修改成功', 'success': True})
        except Exception as e:
            return JsonResponse({'message': '数据库错误', 'success': False})


# 收藏职位
class RecruitsIdCollectView(View):
    def post(self, request, id):
        # 获取用户信息
        user_dict = get_user_dict(request)

        # 判断用户是否合法
        if user_dict:
            # 获取用户
            user = User.objects.get(id=user_dict['user_id'])
        else:
            return JsonResponse({'message': '未登录', 'success': False})

        try:
            recruits = Recruit.objects.get(id=id)

        except Exception as e:
            return JsonResponse({'message': '数据库错误', 'success': False})

        # 添加数据
        users = recruits.users.all()
        count = users.count()

        # 用户是否收藏
        if user in users:
            # 取消收藏
            recruits.users.remove(user)
            count -= 1
        else:
            # 收藏
            recruits.users.add(user)
            count += 1

        return JsonResponse({'message': '收藏成功', 'success': True})
